#include <iostream>

const int N = 4;

bool isSafe(int board[N][N], int row, int col) {
    // 检查同一列是否有皇后
    for (int i = 0; i < row; ++i) {
        if (board[i][col] == 1) {
            return false;
        }
    }

    // 检查左上对角线是否有皇后
    for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
        if (board[i][j] == 1) {
            return false;
        }
    }

    // 检查右上对角线是否有皇后
    for (int i = row - 1, j = col + 1; i >= 0 && j < N; --i, ++j) {
        if (board[i][j] == 1) {
            return false;
        }
    }

    return true;
}

bool solveNQueens(int board[N][N], int row) {
    if (row == N) {
        // 打印棋盘
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                std::cout << (board[i][j] ? "Q " : ". ");
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
        return true;
    }

    bool res = false;
    for (int col = 0; col < N; ++col) {
        if (isSafe(board, row, col)) {
            board[row][col] = 1;

            res = solveNQueens(board, row + 1) || res;

            board[row][col] = 0; // 回溯
        }
    }

    return res;
}

int main() {
    int board[N][N] = {0};

    if (!solveNQueens(board, 0)) {
        std::cout << "No solution exists" << std::endl;
    }

    return 0;
}